﻿using System;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Drawing.Imaging;
using System.Threading;
using System.Linq;
using System.Printing;
using System.Drawing.Printing;
using System.Collections.Generic;
using System.Reflection;
using KPhotoPrinter;
using PrintingServer;
using LogLib;
using System.Threading.Tasks;
using PipeClient;

namespace PhotoPrinter
{
    public partial class FormPrintingService : Form
    {    
        #region 专用于异步发送启动消息
        protected IntPtr ParentFormHandle = IntPtr.Zero;
        /// <summary>
        /// 指示是否已经通知主窗体加载完成
        /// </summary>
        protected bool _bNotified = false;
        public string AppName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
        #endregion

        private ucInterfaceList ucPrinterList = null;
        private ucTcpServer ucSocketServer = null;

        public PhotoPrintingServer Server = null;

        public FormPrintingService()
        {
            ucPrinterList = new ucInterfaceList();
            ucSocketServer = new ucTcpServer();
            InitializeComponent();
        }

        public FormPrintingService(string arg)
        {
            if (!string.IsNullOrEmpty(arg))
            {
                ParentFormHandle = (IntPtr)Int32.Parse(arg);
            }
            ucPrinterList = new ucInterfaceList();
            ucSocketServer = new ucTcpServer();
            InitializeComponent();
        }  

        private void InitTabChildPages()
        {
            tabPage2.Controls.Add(ucSocketServer);
            tabPage3.Controls.Add(ucPrinterList);
            ucPrinterList.LoadInterface();
            ucSocketServer.PrintResultUpdated += ucPrinterList.UpdateActionResult;
            Server = ucSocketServer.Server;
            Server.AppExited += OnAppExited;
            ucSocketServer.PrintApps = ucPrinterList.AvailableInterfaces;           
        }

        private void OnInterfacesConfigRefreshed()
        {
            ucPrinterList.OnConfigRefreshed();
            ucSocketServer.PrintApps = ucPrinterList.AvailableInterfaces;
        }

        /// <summary>
        /// 执行关闭程序动作
        /// </summary>
        public void OnAppExited()
        {
            Log.WriteAsync("收到客户端的消息，开始关闭应用程序.");
            this.Close();
        }

        /// <summary>
        /// 通知主窗体该进程启动已经完成
        /// </summary>
        protected void OnAppStartupFinished(int code = 1, string msg = "程序加载成功")
        {
            // 当父窗体为空时，不需要通知
            if (IntPtr.Zero == ParentFormHandle || _bNotified)
            {
                Log.WriteAsync(string.Format("{0}获取父进程主窗口句柄为空，不启用进程监测.", AppName));
                return;
            }
            string sendMsg = string.Format("{0}#{1}#{2}", AppName, code, msg);
            Pipe t = new Pipe(3, sendMsg, "MainStartup");
            Task.Factory.StartNew(new Action(t.run));
            Log.WriteAsync("已经通知主窗体启动完成: " + AppName);
            _bNotified = true;
        }

        private void FormPrinting_FormClosing(object sender, FormClosingEventArgs e)
        {
            Server.ReleaseInterfaces("");
            ucSocketServer.CloseServer();
        }

        private void FormPrinting_Load(object sender, EventArgs e)
        {
            InitTabChildPages();
            bool bInit = false;
            string msg = "";
            if (ucSocketServer.InitServer())
            {
                if (ucSocketServer.StartServer())
                {
                    bInit = true;
                }
                else
                {
                    msg = Server.ErrorMessage;
                }
            }
            else
            {
                msg = Server.ErrorMessage;
            }
            if (ParentFormHandle != IntPtr.Zero)
            {
                if (bInit)
                {
                    if (ucSocketServer.InitInterfaces(out msg))
                    {
                        OnAppStartupFinished();
                    }
                    else
                    {
                        OnAppStartupFinished(0, msg);
                    }
                }
                else
                {
                    OnAppStartupFinished(0, msg);
                }
            }           
        }
    }
}
